<?php
/**
 * Created by MY_MIND.
 * User: WDJ
 * Date: 2018/7/5 0005
 * Time: 15:21
 */
namespace app\index\controller;

use \think\Controller;
use \think\Db;
use app\index\model\Client;

class Purchase extends Controller
{
    /**
     * 客户端在请求商城之前需要传递一些参数
     * uid          游戏玩家ID
     * isBind       是否绑定邀请码
     * code         邀请码，没有绑定则为空
     * type         手机类型[IOS, Android]
     * token        验证字段
     */
    public function getParams()
    {
        if($this->request->isPost()){
            //新建模型，并判断接收参数是否正确
            $client    =     new Client();
            $post      =     $this->request->post();

            if($client->check($post)){
                $data['uid']       =   $post['uid'];
                $ifCode = Db::name('relation')->where(['game_user_id' => $data['uid']])->find();
                if($ifCode){
                    $data['isBind']    =   true;
                    $data['code']      =   $ifCode['invitation_code'];
                }else{
                    $data['isBind']    =    false;
                    $data['code']      =    '';
                }
                $data['type']      =   $post['type'];
//                Session::set('client_info', $data);'https://chuiniu.qiligame.com'

                echo json_encode(['code' => 0, 'flag' => true, 'result' => $this->request->domain().url('index/shop/showCoin', 'jwt='.self::createJwt($data["uid"], $data["type"]))]);exit;
            }else{
                echo json_encode(['code' => 100, 'flag' => false, 'error' => $client->getError()]);exit;
            }

        }
    }

    /**
     * 客户端的请求和打开浏览器不是同一个会话，所以需要用到jwt验证
     */
    public static function createJwt($uid, $type)
    {
        $header     =   ['type' => 'jwt', 'alg' => 'HS256'];
        $payload    =   ['uid'  => $uid, 'type' => $type];
        $signature  =   hash_hmac('SHA256', base64_encode(json_encode($header)) . '.' . base64_encode(json_encode($payload)), '8WhLBLP7suY');;
        return base64_encode(json_encode($header)) . '.' . base64_encode(json_encode($payload)) . '.' . $signature;
    }
}
